<template>
  <!-- dialogVisible自带属性控制弹窗打开关闭 -->
  <el-dialog v-model="state.changePasswordDialog" title="修改密码" width="400px">
    <el-form class="login-form" :label-position="labelPosition" :rules="rules">
			<el-form-item label="请输入您的旧密码" prop="oldPassword">
				<el-input v-model="passwordData.oldPassword" placeholder="请输入您的旧密码" show-password />
			</el-form-item>
			<el-form-item label="请输入您的新密码" prop="newPassword">
				<el-input v-model="passwordData.newPassword" placeholder="请输入您的新密码" show-password />
			</el-form-item>
		</el-form>
    <!-- 底部内容 -->
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="state.changePasswordDialog = false">取消</el-button>
				<el-button type="primary" @click="changeUserPassword">确定</el-button>
			</span>
		</template>
  </el-dialog>
</template>
 
<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import { changePassword } from '@/api/userinfor.js';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
	const router = useRouter()
  
	const labelPosition = ref('top')  // 表单对齐方式
  // 控制弹窗 默认关闭
	const state = reactive({
		changePasswordDialog: false,
	})

  interface passwordData {
		oldPassword : string;
		newPassword : string;
	}
  // 表单对象
	const passwordData : passwordData = reactive({
		oldPassword: '',
		newPassword: '',
	})

  // 表单规则
	const rules = reactive({
		oldPassword: [
      // trigger的值选blur，即失去焦点时进行验证
			{ required: true, message: '请输入您的旧密码', trigger: 'blur' },
		],
		newPassword: [
			{ required: true, message: '请输入您的新密码', trigger: 'blur' },
		],
	})
	
  // 修改密码
  const changeUserPassword = async () => {
    if(passwordData.oldPassword && passwordData.newPassword){
      const res = await changePassword(localStorage.getItem('id'), passwordData.oldPassword, passwordData.newPassword)
      if(res.data.status == 0){
        ElMessage({
          message: '密码修改成功',
          type: 'success',
        })
        state.changePasswordDialog = false
        router.push('/login')
      }else{
        ElMessage.error('密码输入错误！')
      }
    }else{
      ElMessage.error('输入错误！')
    }
  }


  // 打开修改密码的弹窗
	const open = () => {
		state.changePasswordDialog = true
	}
  defineExpose({
		open
	})
</script>
 
<style lang="scss" scoped>
  
</style>
